<template>
  <div ref="editor"></div>
</template>

<script>
import Quill from "quill";
// import { ImageDrop } from 'quill-image-drop-module';
import { Loading } from "element-ui";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

// Quill.register('modules/imageDrop', ImageDrop);

export default {
  name: "d2-quill",
  props: {
    value: {
      type: String,
      required: false,
      default: ""
    }
  },
  data() {
    return {
      // 设置title 提示
      toolbarTips: [
        { Choice: ".ql-bold", title: "加粗 (Ctrl+B)" },
        { Choice: ".ql-italic", title: "倾斜 (Ctrl+I)" },
        { Choice: ".ql-underline", title: "下划线 (Ctrl+U)" },
        { Choice: ".ql-header", title: "段落格式" },
        { Choice: ".ql-strike", title: "删除线" },
        { Choice: ".ql-blockquote", title: "块引用" },
        { Choice: ".ql-code-block", title: "插入代码段" },
        { Choice: ".ql-size", title: "字体大小" },
        { Choice: '.ql-list[value="ordered"]', title: "编号列表" },
        { Choice: '.ql-list[value="bullet"]', title: "项目列表" },
        { Choice: '.ql-header[value="1"]', title: "h1" },
        { Choice: '.ql-header[value="2"]', title: "h2" },
        { Choice: ".ql-align", title: "对齐方式" },
        { Choice: ".ql-color", title: "字体颜色" },
        { Choice: ".ql-background", title: "背景颜色" },
        { Choice: ".ql-image", title: "图像" },
        { Choice: ".ql-video", title: "视频" },
        { Choice: ".ql-link", title: "添加链接" },
        { Choice: ".ql-formula", title: "插入公式" },
        { Choice: ".ql-clean", title: "清除格式" },
        { Choice: '.ql-indent[value="-1"]', title: "向左缩进" },
        { Choice: '.ql-indent[value="+1"]', title: "向右缩进" },
        { Choice: ".ql-header .ql-picker-label", title: "标题大小" },
        {
          Choice: '.ql-header .ql-picker-item[data-value="1"]',
          title: "标题一"
        },
        {
          Choice: '.ql-header .ql-picker-item[data-value="2"]',
          title: "标题二"
        },
        {
          Choice: '.ql-header .ql-picker-item[data-value="3"]',
          title: "标题三"
        },
        {
          Choice: '.ql-header .ql-picker-item[data-value="4"]',
          title: "标题四"
        },
        {
          Choice: '.ql-header .ql-picker-item[data-value="5"]',
          title: "标题五"
        },
        {
          Choice: '.ql-header .ql-picker-item[data-value="6"]',
          title: "标题六"
        },
        { Choice: ".ql-header .ql-picker-item:last-child", title: "标准" },
        {
          Choice: '.ql-size .ql-picker-item[data-value="small"]',
          title: "小号"
        },
        {
          Choice: '.ql-size .ql-picker-item[data-value="large"]',
          title: "大号"
        },
        {
          Choice: '.ql-size .ql-picker-item[data-value="huge"]',
          title: "超大号"
        },
        { Choice: ".ql-size .ql-picker-item:nth-child(2)", title: "标准" },
        { Choice: ".ql-align .ql-picker-item:first-child", title: "居左对齐" },
        {
          Choice: '.ql-align .ql-picker-item[data-value="center"]',
          title: "居中对齐"
        },
        {
          Choice: '.ql-align .ql-picker-item[data-value="right"]',
          title: "居右对齐"
        },
        {
          Choice: '.ql-align .ql-picker-item[data-value="justify"]',
          title: "两端对齐"
        },
        { Choice: ".ql-table", title: "插入表格" },
        { Choice: ".ql-table-insert-row", title: "插入行" },
        { Choice: ".ql-table-insert-column", title: "插入列" },
        { Choice: ".ql-table-delete-row", title: "删除当前行" },
        { Choice: ".ql-table-delete-column", title: "删除当前列" }
      ],
      videoUploadTag: false,
      Quill: undefined,
      currentValue: "",
      options: {
        theme: "snow",
        bounds: document.body,
        debug: "warn",
        modules: {
          clipboard: {
            // 粘贴版，处理粘贴时候的自带样式
            // matchers: [[Node.ELEMENT_NODE, this.HandleCustomMatcher]]
          },
          table: true,
          // imageDrop: true,
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"],
              ["blockquote", "code-block"],
              [{ list: "ordered" }, { list: "bullet" }],
              // [{ 'script': 'sub' }, { 'script': 'super' }],
              // [{ 'indent': '-1' }, { 'indent': '+1' }],
              // [{ 'direction': 'rtl' }],
              [
                {
                  size: [
                    "10px",
                    "12px",
                    "14px",
                    "16px",
                    "20px",
                    "24px",
                    "36px",
                    false
                  ]
                }
              ],
              [{ header: [1, 2, 3, 4, 5, 6, true] }],

              [{ color: [] }, { background: [] }],
              // [{ 'font': [] }],
              [{ align: [] }],
              ["clean"],
              ["link"],
              ["image", "video"],
              [
                { table: "TD" },
                { "table-insert-row": "TIR" },
                { "table-insert-column": "TIC" },
                { "table-delete-row": "TDR" },
                { "table-delete-column": "TDC" }
              ]
            ],
            handlers: {
              // 插入表格
              table: function(val) {
                this.quill.getModule("table").insertTable(2, 3);
              },
              // 插入表格行
              "table-insert-row": function() {
                this.quill.getModule("table").insertRowBelow();
              },
              // 插入表格列
              "table-insert-column": function() {
                this.quill.getModule("table").insertColumnRight();
              },
              // 删除表格行
              "table-delete-row": function() {
                this.quill.getModule("table").deleteRow();
              },
              // 删除表格列
              "table-delete-column": function() {
                this.quill.getModule("table").deleteColumn();
              }
            }
          }
        },
        placeholder: "书写你的内容",
        readOnly: false
      }
    };
  },
  watch: {
    value: {
      handler(val) {
        // 确认是新的值
        if (val !== this.currentValue) {
          this.currentValue = val;
          // 尝试更新
          if (this.Quill) {
            this.Quill.clipboard.dangerouslyPasteHTML(this.value);
          }
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.init();
    this.autotip();
    // 为自定义表格加上图标样式
    document.querySelector(
      ".ql-table-insert-row"
    ).innerHTML = `<svg viewbox="0 0 18 18">
  <g class="ql-fill ql-stroke ql-thin ql-transparent">
    <rect height="3" rx="0.5" ry="0.5" width="7" x="4.5" y="2.5"></rect>
    <rect height="3" rx="0.5" ry="0.5" width="7" x="4.5" y="12.5"></rect>
  </g>
  <rect class="ql-fill ql-stroke ql-thin" height="3" rx="0.5" ry="0.5" width="7" x="8.5" y="7.5"></rect>
  <polygon class="ql-fill ql-stroke ql-thin" points="4.5 11 2.5 9 4.5 7 4.5 11"></polygon>
  <line class="ql-stroke" x1="6" x2="4" y1="9" y2="9"></line>
</svg>`;
    document.querySelector(
      ".ql-table-insert-column"
    ).innerHTML = `<svg viewbox="0 0 18 18">
  <g class="ql-fill ql-transparent">
    <rect height="10" rx="1" ry="1" width="4" x="12" y="2"></rect>
    <rect height="10" rx="1" ry="1" width="4" x="2" y="2"></rect>
  </g>
  <path class="ql-fill" d="M11.354,4.146l-2-2a0.5,0.5,0,0,0-.707,0l-2,2A0.5,0.5,0,0,0,7,5H8V6a1,1,0,0,0,2,0V5h1A0.5,0.5,0,0,0,11.354,4.146Z"></path>
  <rect class="ql-fill" height="8" rx="1" ry="1" width="4" x="7" y="8"></rect>
</svg>`;
    document.querySelector(
      ".ql-table-delete-row"
    ).innerHTML = `<svg viewbox="0 0 18 18">
  <g class="ql-fill ql-stroke ql-thin ql-transparent">
    <rect height="3" rx="0.5" ry="0.5" width="7" x="4.5" y="2.5"></rect>
    <rect height="3" rx="0.5" ry="0.5" width="7" x="4.5" y="12.5"></rect>
  </g>
  <rect class="ql-fill ql-stroke ql-thin" height="3" rx="0.5" ry="0.5" width="7" x="8.5" y="7.5"></rect>
  <line class="ql-stroke ql-thin" x1="6.5" x2="3.5" y1="7.5" y2="10.5"></line>
  <line class="ql-stroke ql-thin" x1="3.5" x2="6.5" y1="7.5" y2="10.5"></line>
</svg>`;
    document.querySelector(
      ".ql-table-delete-column"
    ).innerHTML = `<svg viewbox="0 0 18 18">
  <g class="ql-fill ql-transparent">
    <rect height="10" rx="1" ry="1" width="4" x="2" y="6"></rect>
    <rect height="10" rx="1" ry="1" width="4" x="12" y="6"></rect>
  </g>
  <rect class="ql-fill" height="8" rx="1" ry="1" width="4" x="7" y="2"></rect>
  <path class="ql-fill" d="M9.707,13l1.146-1.146a0.5,0.5,0,0,0-.707-0.707L9,12.293,7.854,11.146a0.5,0.5,0,0,0-.707.707L8.293,13,7.146,14.146a0.5,0.5,0,1,0,.707.707L9,13.707l1.146,1.146a0.5,0.5,0,0,0,.707-0.707Z"></path>
</svg>`;
    // var box = document.querySelectorAll(".ql-picker-label");
    // box[0].classList.add("abc");
    // box[0].classList.add("abc1");
    // // box[1].classList.add("abc");
    // // box[1].classList.add("abc1");
    // var box_svg1 = box[0];
    // var box_svg2 = box[1];
    // var box_svg3 = box[2];
    // box_svg1.getElementsByTagName("svg")[0].style.float = "right";
    // box_svg2.getElementsByTagName("svg")[0].style.float = "right";
    // box_svg3.getElementsByTagName("svg")[0].style.float = "right";
  },
  methods: {
    autotip() {
      for (let item of this.toolbarTips) {
        let tip = document.querySelector(item.Choice);
        if (!tip) {
          continue;
        } else {
          tip.setAttribute("title", item.title);
        }
      }
    },
    init() {
      const editor = this.$refs.editor;
      // 初始化编辑器
      this.Quill = new Quill(editor, this.options);
      // 默认值
      this.Quill.clipboard.dangerouslyPasteHTML(this.currentValue);
      // 绑定事件
      this.Quill.on("text-change", (delta, oldDelta, source) => {
        const html = this.$refs.editor.children[0].innerHTML;
        const text = this.Quill.getText();
        const quill = this.Quill;
        // 更新内部的值
        this.currentValue = html;
        // 发出事件 v-model
        this.$emit("input", html);
        // 发出事件
        this.$emit("change", { html, text, quill });
      });
      // 将一些 quill 自带的事件传递出去
      this.Quill.on("text-change", (delta, oldDelta, source) => {
        this.$emit("text-change", delta, oldDelta, source);
      });
      this.Quill.on("selection-change", (range, oldRange, source) => {
        this.$emit("selection-change", range, oldRange, source);
      });
      this.Quill.on("editor-change", (eventName, ...args) => {
        this.$emit("editor-change", eventName, ...args);
      });
      //  自定义图片上传
      var toolbar = this.Quill.getModule("toolbar");
      toolbar.addHandler("image", () => {
        var fileInput = toolbar.container.querySelector(
          "input.ql-image[type=file]"
        );
        if (fileInput == null) {
          fileInput = document.createElement("input");
          fileInput.setAttribute("type", "file");
          fileInput.setAttribute(
            "accept",
            "image/png, image/gif, image/jpeg, image/bmp, image/x-icon"
          );
          fileInput.classList.add("ql-image");
          fileInput.addEventListener("change", async () => {
            if (fileInput.files != null && fileInput.files[0] != null) {
              let size = fileInput.files[0].size;
              const isLt2M = size / 1024 / 1024 < 2;

              if (!isLt2M) {
                this.$message.error("上传图片大小不能超过 2MB!");
                return false;
              } else {
                let loadingInstance = Loading.service({
                  // 声明一个loading对象
                  lock: true, // 是否锁屏
                  text: "上传中", // 加载动画的文字
                  spinner: "el-icon-loading", // 引入的loading图标
                  background: "rgba(0, 0, 0, 0.8)", // 背景颜色
                  target: ".el-table, .table-flex, .region", // **需要遮罩的区域，这里写要添加loading的选择器**
                  fullscreen: false,
                  customClass: "loadingclass" // **遮罩层新增类名，如果需要修改loading的样式**
                });
                let res = await this.$api.editPicUpload(fileInput.files[0]);
                loadingInstance.close();
                var range = this.Quill.getSelection();
                if (range) {
                  fileInput.value = null;
                  //  在当前光标位置插入图片
                  toolbar.quill.insertEmbed(
                    range.index,
                    "image",
                    res.data.picUrl
                  );
                  //  将光标移动到图片后面
                  toolbar.quill.setSelection(range.index + 1);
                }
              }
            }
          });
          toolbar.container.appendChild(fileInput);
        }
        fileInput.click();
      });
      toolbar.addHandler("video", () => {
        var fileInput1 = toolbar.container.querySelector(
          "input.ql-video[type=file]"
        );
        if (fileInput1 == null) {
          fileInput1 = document.createElement("input");
          fileInput1.setAttribute("type", "file");
          fileInput1.setAttribute("accept", "video/*");
          fileInput1.classList.add("ql-video");
          fileInput1.addEventListener("change", async () => {
            if (fileInput1.files != null && fileInput1.files[0] != null) {
              let size = fileInput1.files[0].size;
              const isLt50M = size / 1024 / 1024 < 50;

              if (!isLt50M) {
                this.$message.error("上传视频大小不能超过 50MB!");
                return false;
              } else {
                let loadingInstance = Loading.service({
                  // 声明一个loading对象
                  lock: true, // 是否锁屏
                  text: "上传中", // 加载动画的文字
                  spinner: "el-icon-loading", // 引入的loading图标
                  background: "rgba(0, 0, 0, 0.8)", // 背景颜色
                  target: ".el-table, .table-flex, .region", // **需要遮罩的区域，这里写要添加loading的选择器**
                  fullscreen: false,
                  customClass: "loadingclass" // **遮罩层新增类名，如果需要修改loading的样式**
                });
                let res = await this.$api.videoUpload(fileInput1.files[0]);
                loadingInstance.close();
                var range = this.Quill.getSelection();
                if (range) {
                  fileInput1.value = null;
                  //  在当前光标位置插入是视频
                  toolbar.quill.insertEmbed(
                    range.index,
                    "video",
                    res.data.picUrl
                  );
                  //  将光标移动到视频
                  toolbar.quill.setSelection(range.index + 1);
                }
              }
            }
          });
        }
        fileInput1.click();
      });
    }
  }
};
</script>

<style lang="scss">
span.ql-size.ql-picker {
}
span.ql-picker-label > svg {
  // height: 100%;
}
.ql-container {
    font-size:16px;
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="10px"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="10px"]::before {
  content: "10px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="12px"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="12px"]::before {
  content: "12px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="14px"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="14px"]::before {
  content: "14px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="16px"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="16px"]::before {
  content: "16px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="20px"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="20px"]::before {
  content: "20px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="24px"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="24px"]::before {
  content: "24px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="36px"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="36px"]::before {
  content: "36px";
}
.ql-formats {
  margin-right: 0 !important;
  text-align: left;
  .ql-size.ql-picker {
    width: 72px;
  }
}
</style>
